<template>
  <div>
    <el-breadcrumb separator-class="ArrowRight">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>后台用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <!-- 查询表单 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入用户名"
            v-model="queryInfo.name"
            clearable
            @clear="getAdmininfos"
            @change="getAdmininfos(-1)"
          >
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="showAddAdminInfoDialog"
            >添加</el-button
          >
        </el-col>
      </el-row>
      <!-- 管理员列表 -->
      <el-table :data="adminlist" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="name"></el-table-column>
        <el-table-column label="角色" prop="role.roleName"></el-table-column>
        <el-table-column label="状态">
          <template v-slot="scope">
            <el-tag v-if="scope.row.delState == 0" type="success" size="mini"
              >正常</el-tag
            >
            <el-tag v-else type="danger" size="mini">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column min-width="50px" label="操作" width="300">
          <template v-slot="scope">
            <div v-if="scope.row.delState === 0">
              <el-tooltip
                class="item"
                effect="dark"
                content="修改"
                placement="top"
                :enterable="false"
              >
                <el-button
                  type="primary"
                  icon="Edit"
                  size="mini"
                  @click="openEditAdminInfoDialog(scope.row.id)"
                >修改</el-button>
              </el-tooltip>
              <el-tooltip
                class="item"
                effect="dark"
                content="禁用"
                placement="top"
                :enterable="false"
              >
                <el-button
                  type="danger"
                  icon="Delete"
                  size="mini"
                  @click="disableAdminInfo(scope.row.id)"
                >禁用</el-button>
              </el-tooltip>
              <el-tooltip
                class="item"
                effect="dark"
                content="分配角色"
                placement="top"
                :enterable="false"
              >
                <el-button
                  type="warning"
                  icon="Setting"
                  size="mini"
                  @click="openSetRoleDialog(scope.row)"
                >设置</el-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.curPage"
        :page-sizes="[5, 10, 20]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      v-model="setRoleDialogVisible"
      width="40%"
      @close="handleSetRoleDialogClosed"
    >
      <span>
        <div>
          <p v-if="admininfo">用户名: {{ admininfo.name }}</p>
          <p v-if="admininfo && admininfo.role">
            角色名: {{ admininfo.role.roleName }}
          </p>
          <p v-if="admininfo && !admininfo.role">角色名: 无</p>
          <p>
            新角色名:
            <el-select v-model="newRoleId" placeholder="请选择">
              <el-option
                v-for="item in rolelist"
                :key="item.roleId"
                :label="item.roleName"
                :value="item.roleId"
              ></el-option>
            </el-select>
          </p>
        </div>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="powerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加管理员对话框 -->
    <el-dialog
      title="添加后台管理员"
      v-model="addAdminInfoDialogVisible"
      width="30%"
      @close="resetAddAdminInfoForm()"
    >
      <el-form
        ref="addAdminInfoFormRef"
        :model="addAdminInfoForm"
        :rules="addAdminInfoFormRules"
        label-width="0px"
        class="login-form"
      >
        <!-- 管理员名称 -->
        <el-form-item prop="name">
          <el-input
            v-model="addAdminInfoForm.name" 
            placeholder="请输入管理员名称"
          ></el-input>
        </el-form-item>
        <!-- 管理员密码 -->
        <el-form-item prop="pwd">
          <el-input
            v-model="addAdminInfoForm.pwd" 
            placeholder="请输入管理员密码"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addAdminInfoDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addAdminInfo()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改管理员对话框 -->
    <el-dialog
      title="修改后台管理员"
      v-model="editAdminInfoDialogVisible"
      width="30%"
    >
      <el-form
        ref="editAdminInfoFormRef"
        :model="editAdminInfoForm"
        :rules="editAdminInfoFormRules"
        label-width="0px"
        class="login-form"
      >
        <!-- 管理员名称 -->
        <el-form-item prop="name">
          <el-input
            v-model="editAdminInfoForm.name" 
            placeholder="请输入管理员名称"
          ></el-input>
        </el-form-item>
        <!-- 管理员密码 -->
        <el-form-item prop="pwd">
          <el-input
            v-model="editAdminInfoForm.pwd" 
            placeholder="请输入管理员密码"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editAdminInfoDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editAdminInfo()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from "vue";
 
    const { proxy } = getCurrentInstance();
    // 封装查询参数
    const queryInfo = reactive({
      name: "",
      curPage: 1,
      pageSize: 5,
    });
    // 保存管理员列表
    const adminlist = ref(null);
    // 保存后台用户总记录数
    const total = ref(0);
    // 控制角色设置对话框是否可见
    const setRoleDialogVisible = ref(false);
    // 控制添加管理员对话框是否可见
    const addAdminInfoDialogVisible = ref(false);
    // 控制修改管理员对话框是否可见
    const editAdminInfoDialogVisible = ref(false);
    // 待分配角色的管理员对象
    const admininfo = ref(null);
    // 保存所有角色列表
    const rolelist = ref(null);
    // 分配的新角色id
    const newRoleId = ref("");

    // 保存添加管理员表单数据
    const addAdminInfoForm = reactive({
      name: "",
      pwd: "",
    });
    // 保存修改管理员表单数据
    const editAdminInfoForm = reactive({
      id: "",
      name: "",
      pwd: "",
    });
    // 指定添加管理员表单被引用时的名称和标识
    const addAdminInfoFormRef = ref(null);
    // 指定修改管理员表单被引用时的名称和标识
    const editAdminInfoFormRef = ref(null);
    // 设置添加管理员表单验证规则
    const addAdminInfoFormRules = reactive({
      name: [{ required: true, message: "请输入管理员名称", trigger: "blur" }],
      pwd: [{ required: true, message: "请输入管理员密码", trigger: "blur" }],
    });
    // 设置修改管理员表单验证规则
    const editAdminInfoFormRules = reactive({
      name: [{ required: true, message: "请输入管理员名称", trigger: "blur" }],
      pwd: [{ required: true, message: "请输入管理员密码", trigger: "blur" }],
    });


    // 向后台程序发送请求，分页获取管理员列表
    const getAdmininfos = async (flag) => {
      if (flag == 0 || flag == -1) {
        queryInfo.curPage = 1;
      }
      // 分页获取管理员列表
      const { data: res } = await proxy.$axios.get("admininfos", {
        params: {
          name: queryInfo.name,
          curPage: queryInfo.curPage,
          pageSize: queryInfo.pageSize,
        },
      });
      if (res.code != 0) return proxy.$message.error("没有管理员记录!");
      adminlist.value = res.adminInfos;
      total.value = res.total;
    };

    // pageSize改变事件处理函数
    const handleSizeChange = (pageSize) => {
      queryInfo.pageSize = pageSize;
      getAdmininfos();
    };

    // page改变事件处理函数
    const handleCurrentChange = (curPage) => {
      queryInfo.curPage = curPage;
      getAdmininfos();
    };

    // 打开设置角色对话框
    const openSetRoleDialog = async (ai) => {
      admininfo.value = ai;
      // 获取所有角色
      const { data: res } = await proxy.$axios.get("roles/valid");
      rolelist.value = res.data;
      setRoleDialogVisible.value = true;
    };

    // 处理设置角色对话框关闭事件
    const handleSetRoleDialogClosed = () => {
      newRoleId.value = "";
    };
    // 保存角色设置
    const saveRole = async () => {
      if (!newRoleId.value) {
        return proxy.$message.error("请选择一个角色!");
      }
      const { data: res } = await proxy.$axios.put(
        `admininfos/${admininfo.value.id}/role/${newRoleId.value}`
      );
      if (res.code != 0) return proxy.$message.error("角色分配失败!");
      proxy.$message.success("角色分配成功!");
      getAdmininfos();
      setRoleDialogVisible.value = false;
    };

    // 重置添加管理员对话框中的表单
    const resetAddAdminInfoForm = () => {
      addAdminInfoFormRef.value.resetFields();
    };

    // 显示添加管理员对话框
    const showAddAdminInfoDialog = () => {
      addAdminInfoDialogVisible.value = true;
    };

    // 添加管理员
    const addAdminInfo = () => {
      addAdminInfoFormRef.value.validate(async (valid) => {
        if (!valid) return;
        var name = addAdminInfoForm.name;
        var pwd = addAdminInfoForm.pwd;
        // 判断管理员名称是否已存在
        const { data: res1 } = await proxy.$axios.get(`admininfos/name/${name}`);
        if (res1.code !== 0) return proxy.$message.error("该管理员名称已存在!");
        const { data: res2 } = await proxy.$axios.post(`admininfos`, {
          name: name,
          pwd: pwd,
        });
        if (res2.code !== 0) return proxy.$message.error("添加失败!");
        proxy.$message.success("添加成功!");
        getAdmininfos();
        addAdminInfoDialogVisible.value = false;
      });
    };

    // 打开修改对话框
    const openEditAdminInfoDialog = async (id) => {
      editAdminInfoDialogVisible.value = true;
      const { data: res } = await proxy.$axios.get(`admininfos/id/${id}`);
      console.log(res.adminInfo);
      if (res.code != 0) return proxy.$message.error("获取数据失败!");
      editAdminInfoForm.name = res.adminInfo.name;
      editAdminInfoForm.pwd = res.adminInfo.pwd;
      editAdminInfoForm.id = res.adminInfo.id;
    };

    // 修改
    const editAdminInfo = () => {
      editAdminInfoFormRef.value.validate(async (valid) => {
        if (!valid) return;
        var name = editAdminInfoForm.name;
        var pwd = editAdminInfoForm.pwd;
        var id = editAdminInfoForm.id;
        // 判断管理员名称是否已存在
        const { data: res1 } = await proxy.$axios.get(
          `admininfos/name/${name}/id/${id}`
        );
        if (res1.code !== 0) return proxy.$message.error("该管理员名称已存在!");
        const { data: res2 } = await proxy.$axios.put(`admininfos`, {
          name: name,
          pwd: pwd,
          id: id,
        });
        if (res2.code !== 0) return proxy.$message.error("修改失败!");
        proxy.$message.success("修改成功!");
        getAdmininfos();
        editAdminInfoDialogVisible.value = false;
      });
    };

    // 管理员禁用
    const disableAdminInfo = async (id) => {
      const { data: res } = await proxy.$axios.put(`admininfos/id/${id}/delState`);
      if (res.code !== 0) return proxy.$message.error("禁用失败!");
      proxy.$message.success("禁用成功!");
      getAdmininfos();
    };

    onMounted(() => {
      getAdmininfos();
    });

</script>

<style lang="less" scoped>
</style>

